import React from 'react';
import styles from './style';

let toast = null;
class Toast extends React.Component {

  static propTypes = {
    warn: React.PropTypes.string,
    error: React.PropTypes.string,
    info: React.PropTypes.string,
    success: React.PropTypes.string
  };

  state = {
    //0: NULL
    //1: warn
    //2: error
    //3: info
    //4: success
    type: 0,
    msg: '',
    hidden: true
  };

  constructor(props) {
    super(props);
    toast = this;
  }

  render() {
    const { hidden, type, msg } = this.state;
    const { className:_className, warn, error, info, success} = this.props;
    let className = `${styles.root}`;
    if (type === 1) {
      className += ` ${styles.warn}`;
      if (warn) style.backgroundColor = warn;
    }
    if (type === 2) {
      className += ` ${styles.error}`;
      if (error) style.backgroundColor = error;
    }
    if (type === 3) {
      className += ` ${styles.info}`;
      if (info) style.backgroundColor = info;
    }
    if (type === 4) {
      className += ` ${styles.success}`;
      if (success) style.backgroundColor = success;
    }
    if (hidden) className += ` ${styles.hidden}`;
		if (className) className += ` ${_className}`;

    let _top = window.location.pathname.match(/^\/u|\/onboarding-flows\/staff/)? '0': '50'
    if (window.location.hash.indexOf('#/hr') === 0 && window.location.hash.indexOf('#/hr/index') !== 0) _top = 80
    return (
      <div 
        style={{
          top: `${_top}px`,
          ...(~(document.body.className || '').indexOf('has-modal')? {top: '0px', zIndex: '6000'}: {})
        }}
        className={className}>
        <div>
          <span>{ msg }</span>
        </div>
      </div>
    );
  }
}

let timeout = null;
['warn', 'error', 'info', 'success']
  .forEach((action, i) => {
    Toast[action] = (msg, keep) => {
      if (!msg) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        Toast.hide()
        return
      }
      if (toast === null) throw Error('need a Toast Component initial.')
      toast.setState({
        type: i+1,
        msg,
        hidden: false
      });

      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }

      if (!keep) {
        timeout = setTimeout(() => {
          toast.setState({
            hidden: true
          })
          timeout = null;
        }, 2000);
      }
    };
  });

// hide keep toast
Toast.hide = () => {
  if (timeout) return
  toast.setState({
    hidden: true
  })
}

export default Toast;
export const error = Toast.error
export const warn = Toast.warn
export const info = Toast.info
export const success = Toast.success
